import { weAtob } from '../../../utils/jwt-code.js';
import RecNPManager from './nativeAudio.js';

export default class AudioStreamPlayer {
    constructor() {
        this.platform = this.getPlatform();

        // 通用队列管理
        this.audioQueue = [];
        this.isPlaying = false;
        this.currentAudioIndex = 0;
        this.audioContext = null;
        this.scheduledTime = 0;
        this.sources = [];

        // 微信小程序 Web Audio API 相关属性
        this.weixinWebAudioContext = null;
        this.weixinAudioQueue = [];
        this.weixinScheduledTime = 0;
        this.weixinSources = [];
        this.useWeixinWebAudio = true;

        // 音量控制，减少回声
        this.playbackVolume = 0.6; // 降低播放音量

        // App环境音频播放器相关属性（按文档实现顺序播放队列）
        this.appPcmPlayer = null;

        // 根据平台初始化不同的音频播放器
        this.initAudioPlayer();
    }

    // 获取当前平台
    getPlatform() {
        let platform = 'h5';
        // #ifdef MP-WEIXIN
        platform = 'mp-weixin';
        // #endif

        // #ifdef H5
        const userAgent = navigator.userAgent.toLowerCase();

        if (userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1) {
            platform = 'safari';
        }
        platform = 'h5';
        // #endif

        // #ifdef APP-PLUS
        platform = 'app';
        // #endif

        return platform;
    }

    RecNP_CallAsync(action, args) {
        return RecNPManager.call(action, args || {});
    }

    // 检查微信小程序环境下的 API 支持情况
    checkWeixinAPISupport() {
        // #ifdef MP-WEIXIN
        const support = {
            createWebAudioContext: typeof wx.createWebAudioContext === 'function',
            base64ToArrayBuffer: typeof uni.base64ToArrayBuffer === 'function',
            fileSystem: typeof wx.getFileSystemManager === 'function',
            env: typeof wx.env === 'object' && wx.env.USER_DATA_PATH,
        };

        return support;
        // #endif
    }

    // 初始化音频播放器
    initAudioPlayer() {
        switch (this.platform) {
            case 'mp-weixin':
                this.initWeixinPlayer();
                break;
            case 'safari':
                this.initSafariPlayer();
                break;
            case 'h5':
                this.initH5Player();
                break;
            case 'app':
                this.initAppPlayer();
                break;
        }
    }

    // App环境音频播放器初始化（按文档）
    async initAppPlayer() {
        // #ifdef APP-PLUS
        try {
            // 绑定一次原生事件
            if (!this._appJsCallBound) {
                RecNPManager.bindJsCallOnce();
                this._onLogHandler = data => {
                    if (!data || data.action !== 'onLog') return;
                };
                this._onPcmEventHandler = data => {
                    if (!data || data.action !== 'onPcmPlayerEvent') return;
                    console.log(data);
                };
                RecNPManager.on('onLog', this._onLogHandler);
                RecNPManager.on('onPcmPlayerEvent', this._onPcmEventHandler);
                this._appJsCallBound = true;
            }

            if (!this.appPcmPlayer) {
                const res = await this.RecNP_CallAsync('pcmPlayer_create', {
                    sampleRate: 24000,
                    realtime: false, // 针对300ms包优化，允许更大延迟
                    timeUpdateInterval: 10, // 适中的心跳频率
                    setSpeakerOff: { off: false, headset: false }, // 扬声器外放
                });
                this.appPcmPlayer = res.player;
            }
        } catch (error) {
            console.error('App环境音频播放器初始化失败:', error);
        }
        // #endif
    }

    // 微信小程序音频播放器初始化
    initWeixinPlayer() {
        // 检查 API 支持情况
        const apiSupport = this.checkWeixinAPISupport();

        // 优先尝试使用 Web Audio API
        if (apiSupport.createWebAudioContext) {
            try {
                // #ifdef MP-WEIXIN
                this.weixinWebAudioContext = wx.createWebAudioContext({
                    sampleRate: 24000,
                });
                this.weixinScheduledTime = this.weixinWebAudioContext.currentTime;
                this.useWeixinWebAudio = true;

                // 确保音频上下文处于运行状态
                if (this.weixinWebAudioContext.state === 'suspended') {
                    this.weixinWebAudioContext.resume();
                }

                return;
                // #endif
            } catch (error) {
                console.error('微信小程序 Web Audio API 初始化失败:', error);
            }
        } else {
            console.error('微信小程序不支持 Web Audio API');
        }
    }

    // Safari浏览器音频播放器初始化
    initSafariPlayer() {
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
                sampleRate: 24000,
            });
            this.scheduledTime = this.audioContext.currentTime;
            this.sources = [];

            // Safari需要用户交互后才能播放音频
            this.audioContext.resume();
        } catch (error) {
            console.error('Safari音频上下文初始化失败:', error);
        }
    }

    // H5音频播放器初始化
    initH5Player() {
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
                sampleRate: 24000,
            });
            this.scheduledTime = this.audioContext.currentTime;
            this.sources = [];
        } catch (error) {
            console.error('H5音频上下文初始化失败:', error);
        }
    }

    // 添加音频数据
    addAudio(base64Data) {
        switch (this.platform) {
            case 'mp-weixin':
                if (this.useWeixinWebAudio) {
                    // 确保用户交互后音频上下文已启动
                    this.ensureWeixinAudioContextReady();
                    this.triggerUserInteraction();
                    this.addAudioWeixinWebAPI(base64Data);
                } else {
                    console.error('微信小程序 Web Audio API 不可用');
                }
                break;
            case 'safari':
            case 'h5':
                this.addAudioWebAPI(base64Data);
                break;
            case 'app':
                this.addAudioApp(base64Data);
                break;
        }
    }

    // App环境音频播放器添加音频（针对300ms包优化）
    addAudioApp(base64Data) {
        // #ifdef APP-PLUS
        // 立即开始播放，确保音频连续
        this.RecNP_CallAsync('pcmPlayer_input', {
            player: this.appPcmPlayer,
            pcmDataBase64: base64Data,
        });
        // #endif
    }

    // 确保微信小程序音频上下文准备就绪
    ensureWeixinAudioContextReady() {
        if (this.weixinWebAudioContext && this.weixinWebAudioContext.state === 'suspended') {
            this.weixinWebAudioContext
                .resume()
                .then(() => {})
                .catch(error => {
                    console.error('微信小程序音频上下文恢复失败:', error);
                });
        }
    }

    // 触发用户交互以启动音频播放（微信小程序 Web Audio API 需要）
    triggerUserInteraction() {
        // #ifdef MP-WEIXIN
        if (this.weixinWebAudioContext && this.weixinWebAudioContext.state === 'suspended') {
            // 创建一个静音的音频缓冲区来触发用户交互
            const silentBuffer = this.weixinWebAudioContext.createBuffer(1, 1, 24000);
            const silentSource = this.weixinWebAudioContext.createBufferSource();
            silentSource.buffer = silentBuffer;
            silentSource.connect(this.weixinWebAudioContext.destination);
            silentSource.start(0);
            silentSource.stop(0.001);
        }
        // #endif
    }

    // 微信小程序 Web Audio API 添加音频
    addAudioWeixinWebAPI(base64Data) {
        try {
            // 兼容性处理：优先使用 uni.base64ToArrayBuffer，如果不支持则使用 atob
            let arrayBuffer;
            try {
                // #ifdef MP-WEIXIN
                if (typeof uni.base64ToArrayBuffer === 'function') {
                    arrayBuffer = uni.base64ToArrayBuffer(base64Data);
                    console.log('使用 uni.base64ToArrayBuffer 成功');
                } else {
                    throw new Error('uni.base64ToArrayBuffer not supported');
                }
                // #endif
                // #ifndef MP-WEIXIN
                throw new Error('Not in WeChat Mini Program');
                // #endif
            } catch (error) {
                console.warn('uni.base64ToArrayBuffer 不支持，使用 weAtob 降级处理:', error);
                // 降级到 weAtob 方式
                const binaryString = weAtob(base64Data);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                arrayBuffer = bytes.buffer;
                console.log('使用 weAtob 降级处理成功');
            }

            const pcmData = new Int16Array(arrayBuffer);

            const audioBuffer = this.weixinWebAudioContext.createBuffer(1, pcmData.length, 24000);
            const channelData = audioBuffer.getChannelData(0);

            // 将 Int16Array 转换为 Float32Array
            for (let i = 0; i < pcmData.length; i++) {
                channelData[i] = pcmData[i] / 32768.0;
            }

            this.scheduleWeixinPlayback(audioBuffer);
        } catch (error) {
            console.error('微信小程序 Web Audio API 音频数据处理失败:', error);
        }
    }

    // 微信小程序 Web Audio API 调度播放
    scheduleWeixinPlayback(audioBuffer) {
        try {
            // 确保音频上下文处于运行状态
            if (this.weixinWebAudioContext.state === 'suspended') {
                this.weixinWebAudioContext.resume();
            }

            const source = this.weixinWebAudioContext.createBufferSource();
            source.buffer = audioBuffer;

            // 创建音量控制节点
            const gainNode = this.weixinWebAudioContext.createGain();
            gainNode.gain.value = this.playbackVolume; // 设置播放音量

            // 连接音频节点：source -> gainNode -> destination
            source.connect(gainNode);
            gainNode.connect(this.weixinWebAudioContext.destination);

            const now = this.weixinWebAudioContext.currentTime;
            if (this.weixinScheduledTime < now) {
                this.weixinScheduledTime = now;
            }

            source.start(this.weixinScheduledTime);
            this.weixinScheduledTime += audioBuffer.duration;
            this.weixinSources.push(source);

            source.onended = () => {
                const idx = this.weixinSources.indexOf(source);
            };

            source.onerror = error => {
                console.error('微信小程序 Web Audio 播放错误:', error);
                const idx = this.weixinSources.indexOf(source);
                if (idx !== -1) this.weixinSources.splice(idx, 1);
            };
        } catch (error) {
            console.error('微信小程序 Web Audio 调度播放失败:', error);
        }
    }

    // Web Audio API添加音频
    addAudioWebAPI(base64Data) {
        try {
            const binaryString = atob(base64Data);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }

            const pcmData = new Int16Array(bytes.buffer);
            const audioBuffer = this.audioContext.createBuffer(1, pcmData.length, 24000);
            const channelData = audioBuffer.getChannelData(0);
            for (let i = 0; i < pcmData.length; i++) {
                channelData[i] = pcmData[i] / 32768.0;
            }

            this.schedulePlayback(audioBuffer);
        } catch (error) {
            console.error('Web Audio API音频数据处理失败:', error);
        }
    }

    // 调度播放（Web Audio API）
    schedulePlayback(audioBuffer) {
        const source = this.audioContext.createBufferSource();
        source.buffer = audioBuffer;
        source.connect(this.audioContext.destination);

        const now = this.audioContext.currentTime;
        if (this.scheduledTime < now) {
            this.scheduledTime = now;
        }

        source.start(this.scheduledTime);
        this.scheduledTime += audioBuffer.duration;
        this.sources.push(source);

        source.onended = () => {
            const idx = this.sources.indexOf(source);
            if (idx !== -1) this.sources.splice(idx, 1);
        };
    }

    // 检查播放是否完成
    isPlaybackFinished() {
        switch (this.platform) {
            case 'mp-weixin':
                if (this.useWeixinWebAudio) {
                    return this.weixinSources.length === 0;
                } else {
                    return true;
                }
            case 'safari':
            case 'h5':
                return this.sources.length === 0 && this.audioQueue.length === 0;
            default:
                return true;
        }
    }

    // 停止播放
    stop() {
        switch (this.platform) {
            case 'mp-weixin':
                if (this.useWeixinWebAudio) {
                    this.stopWeixinWebAPI();
                }
                break;
            case 'safari':
            case 'h5':
                this.stopWebAPI();
                break;
            case 'app':
                this.stopAppAudio();
                break;
        }
    }

    // 停止微信小程序 Web Audio API 播放
    stopWeixinWebAPI() {
        this.weixinScheduledTime = this.weixinWebAudioContext.currentTime;
        this.weixinSources.forEach(source => {
            try {
                source.stop();
            } catch (e) {}
        });
        this.weixinSources = [];
    }

    // 停止Web Audio API播放
    stopWebAPI() {
        this.scheduledTime = this.audioContext.currentTime;
        this.sources.forEach(source => {
            try {
                source.stop();
            } catch (e) {}
        });
        this.sources = [];

        // 清空队列
        this.audioQueue = [];
        this.isPlaying = false;
    }

    // 停止App音频播放
    stopAppAudio() {
        // #ifdef APP-PLUS
        if (this.appPcmPlayer) {
            this.RecNP_CallAsync('pcmPlayer_clearInput', {
                player: this.appPcmPlayer,
            })
                .then(() => {
                    this.appAudioQueue = [];
                    this.isAppPlaying = false;
                    console.log('[APP][Player] 已清空输入缓冲并停止');
                })
                .catch(error => {
                    console.error('停止App音频播放失败:', error);
                });
        }
        // #endif
    }

    // 销毁播放器
    destroy() {
        this.stop();

        // 微信小程序销毁
        if (this.platform === 'mp-weixin') {
            if (this.useWeixinWebAudio && this.weixinWebAudioContext) {
                this.weixinWebAudioContext.close();
                this.weixinWebAudioContext = null;
            }
        }

        // Web Audio API销毁
        if (this.audioContext && this.audioContext.state !== 'closed') {
            this.audioContext.close();
        }

        // App环境销毁
        if (this.platform === 'app' && this.appPcmPlayer) {
            const player = this.appPcmPlayer;
            this.appAudioQueue = [];
            this.isAppPlaying = false;
            this.appAwaitFinalize = false;
            this.appFinalizedMode = false;
            if (this.appSeqGuardTimer) {
                clearTimeout(this.appSeqGuardTimer);
                this.appSeqGuardTimer = null;
            }
            this.RecNP_CallAsync('pcmPlayer_destroy', {
                player,
            })
                .then(() => {
                    this.appPcmPlayer = null;
                    console.log('[APP][Player] 已销毁');
                })
                .catch(error => {
                    console.error('销毁App音频播放器失败:', error);
                })
                .finally(() => {
                    if (this._appJsCallBound) {
                        if (this._onLogHandler) RecNPManager.off('onLog', this._onLogHandler);
                        if (this._onPcmEventHandler)
                            RecNPManager.off('onPcmPlayerEvent', this._onPcmEventHandler);
                        this._appJsCallBound = false;
                    }
                });
        }

        this.audioContext = null;
        this.audioQueue = [];
        this.weixinSources = [];
    }
}
